<template>
    <div :class="{'conMain':!ispop}">
        <div class="pop-bg" @click="handleHideModal" v-if="ispop"></div>
        <div :class="['order-maintain-box',{' pop-modal':ispop}]">
            <div class="top-title" v-if="ispop">
                <h3>{{orderTitle}}</h3>
            </div>
            <div class="conMain">
                <div class="side-left order-con">
                    <h3>下单详情</h3>
                    <div class="input-wrap" @click.stop="clickShowClassify">
                        <div class="title"><em>* </em>维修大类:</div>
                        <input class="con-txt classify" readonly v-model="classify" />
                        <div class="clear-btn" v-show="classify != ''" @click="clearInputTxt('classify')">&times;</div>
                    </div>
                    <div class="input-wrap">
                        <div class="title"><em>* </em>维修小类:</div>
                        <input class="con-txt catalog" v-model="catalog" disabled="disabled"/>
                    </div>
                    <div class="input-wrap" @click.stop="clickShowRoom()">
                        <div class="title"><em>* </em>申报位置:</div>
                        <input class="con-txt start" v-model="starts" disabled="disabled" :title="starts"/>
                    </div>
                    <div class="input-wrap" @click.stop="clickShowStart()">
                        <input type="button" value="重设申报位置"/>
                    </div>
                    <div class="input-wrap">
                        <div class="title con-area-title"><em>* </em>详情描述:</div>
                        <div>
                            <textarea type="text" :class="['con-area desc-area',{'big':form.desc}]" v-model="form.desc" :placeholder="descTips" maxlength="250"></textarea>
                        </div>
                    </div>
                    <div class="input-wrap">
                        <div class="title con-area-title"><em>* </em>联系人:</div>
                        <div>
                            <textarea :class="['con-area contact-area',{'big':form.contact}]" v-model="form.contact" :placeholder="contactTips" maxlength="30"></textarea>
                        </div>
                        <!-- <input class="con-txt start" v-model="contact" :placeholder="contactTips"/> -->
                    </div>
                    <div class="input-wrap"><button class="btn" @click="submit()">{{submitTxt}}</button></div>
                </div>

                <div class="side-right noTitle side-right2" v-if="isShowList">
                    <div class="main-part">
                        <ul v-if="currType == 0">
                            <li :class="['li-item', form.classifyId == item.id ? 'li-active' : '']" v-for="item in classifyLis" :key="item.id" @click="switchCatalogLis(item.id, item.title)">
                                <span>{{item.title}}</span>
                            </li>
                        </ul>
                        <ul v-if="currType == 1">
                            <li :class="['li-item', form.catalogId == item.id ? 'li-active' : '']" v-for="item in catalogLis" :key="item.id" @click="saveLisItem(item.id, item.title, 1)">
                                <span>{{item.title}}</span>
                            </li>
                        </ul>
                        <ul class="itemUl"  v-if="currType == 7">
                            <li class="itemLi" v-for="(item, index) in roomLis" :key="index" @click="selectStartRoom(item.name)">
                                <span>{{item.name}}</span>
                            </li>
                        </ul>
                    </div>
                </div>

                <div class="side-right noTitle side-right2 ks-list" v-if="isShowKsList">
                    <div class="main-part">
                        <ul>
                            <li class="li-item" v-for="item in ksLis" :key="item.id" @click="switchKsLis(item.id, item.name)">
                                <span>{{item.name}}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {
    mtAddressUrl,
    mtSubmitUrl ,
    mtClassifyUrl,
    mtTopClassifyUrl
} from '../common/ajax'
import common from '../common/com'
export default {
    props:{
        isShowModal:{
            type: Boolean,
            default: false
        },
        start:{
            type: String,
            default: ''
        },
        roomLis:{
            type: Array,
            default: () => []
        },
        ispop:{
            type: Boolean,
            default: false
        }
    },
    data(){
        return{
            dataLis:[],
            topDataLis:[],
            orderTitle: Cookies.get('categoryid') != '33' ? '维修下单' : '新增服务受理工单',
            submitTxt: '确定下单',  // 提交的时候改为"提交中..."
            descTips: '请尽可能的描述问题，让我们的师傅更好的为您服务~如：30病房抽风机坏了',
            contactTips: '请备注您的工号/姓名/电话，其中一项信息即可。方便师傅联系您，确定准确位置。',
            classifyLis: [],
            catalogLis: [],
            classify: '',
            catalog: '',
            form: {
                classifyId: '',
                catalogId: '',
                desc: '',
                contact: ''
            },
            addressData: [],
            isShowCommon: false,
            catalogState: false,
            isShowList: true,   // 显示大小类、起点科室等
            isShowKsList: false,    // 显示5层地址
            fullName: [],
            currFloor: 0,
            starts: '',     // 最后要提交的地址，默认是外部传入的起点地址
            currType: 0,    // 大类:0 小类:1
            ksLis: [],   // 记录当前层级的科室地址
            startSite: sessionStorage.getItem('preRomm') || '',
            isHandle:true
        }
    },
    created(){
        this.loadMtClassify();
        this.loadMtCommon();
        this.loadNewAddress();
    },
    mounted(){
        setTimeout(()=>{
            let sarr = this.start.split(' ')
            let rarr = this.start.split(' / ')
            if(sarr[2] && rarr[1]){
                this.starts = sarr[0] + ' ' + sarr[1]
                if(this.startSite && this.start.indexOf(this.startSite) != -1){
                    this.starts += ' '+this.startSite
                    this.clickShowClassify()
                }else {

                    this.clickShowRoom()
                }
            }else {
                this.starts = this.start
                this.clickShowClassify()
            }
        },400)

    },
    methods:{
        //获取常用类型
        loadMtCommon(){
            jQuery.ajax({
                url: mtTopClassifyUrl,
                type: 'get',
                dataType: 'json',
                cache: false,
                success: function(data){
                    if(data.success){
                        let arr = [], idxArr = [];
                        data.data.forEach((v, i) => {
                            if(idxArr.indexOf(v.bigid) == -1){
                                idxArr.push(v.bigid)
                                arr.push({
                                    id: v.bigid,
                                    smalls: [{
                                        bid: v.bigid,
                                        id: v.smallid,
                                        title: v.smalltitle
                                    }],
                                    title: v.bigtitle
                                })
                            }else{
                                arr.forEach(v2 => {
                                    if(v2.id == v.bigid){
                                    v2.smalls.push({
                                        bid: v.bigid,
                                        id: v.smallid,
                                        title: v.smalltitle
                                    })
                                }
                            })
                            }
                        });
                        this.topDataLis = arr;
                    }else {
                        throwErrorTips(`获取常用类别失败`,data.msg)
                    }
                }.bind(this)
            })
        },
        //获取大小类
        loadMtClassify(){
            jQuery.ajax({
                url: mtClassifyUrl,
                type:'get',
                dataType: 'json',
                cache: false,
                success: function(data) {
                    if(data.success){
                        this.dataLis = data.data;
                    }else {
                        throwErrorTips(`获取类别失败`,data.msg)
                    }
                }.bind(this)
            });
        },
        //点击选择科室
        clickShowRoom(){
            // common.inputOutline('.start');
            if(this.roomLis.length > 1){
                common.inputOutline('.start');
                this.isShowList = true;
                this.isShowKsList = false;
                // this.selectTab(7);
                this.currType = 7;
            }
        },
        //选择科室
        selectStartRoom(name){
            this.startSite = name;
            sessionStorage.setItem('preRomm',name);
            var arr = this.start.split(' ');
            this.starts = arr[0] + ' ' + arr[1]  + ' '+ name;
            if(this.classify == ''){
                this.clickShowClassify()
            }
        },
        //重选地址
        resetKsAll(){
            this.ksLis = [];
        },
        saveFullName(){
            this.isShowKsList = false;
            this.starts = this.fullName.join(' ');
            this.resetKsAll();
        },
        switchKsLis(id, name){
            this.ksLis = this.ksLis.find(v => id == v.id).vals
            this.fullName.push(name)
            if(this.ksLis.length == 0){
                this.saveFullName()
                return;
            }
        },
        loadNewAddress(){   // 获取科室地址
            jQuery.ajax({
                url: mtAddressUrl,
                type: 'get',
                cache: false,
                success: function(data){
                    if(data.success){
                        this.addressData = data.data.filter(v => v.id != 119 && v.id != 200);
                    }else {
                        throwErrorTips('获取地址失败',data.msg)
                    }
                }.bind(this)
            })
        },
        clickShowStart(){
            this.isShowList = false;
            this.isShowKsList = true;
            this.fullName = [];
            this.ksLis = this.addressData.map(v => v)
        },
        //选择类型
        clickShowClassify(){
            common.inputOutline('.classify');
            this.currType = 0;
            this.isShowList = true;
            this.isShowKsList = false;
            this.resetClassifyAndCatalog();
            this.catalogLis = []
            if(this.isShowCommon){
                this.isShowCommon = false;
                this.switchClassifyLis(1);
                return;
            }else{
                this.switchClassifyLis(0);
            }
        },
        clickShowCatalog(){
//            if(this.form.classifyId){
//                this.switchCatalogLis(this.form.classifyId,this.classify)
//            }
        },
        clearInputTxt(){    // 清空大小类内容，并返回显示大类项list
            this.classify = '';
            this.catalog = '';
            this.catalogLis = [];
            this.resetClassifyAndCatalog();
            this.switchClassifyLis(0);
            this.isShowList = false;
        },
        //提交
        checkForm(){    // 检查form是否填写完整
            if(this.form.classifyId == ''){
                this.$Message({type:'error',message:'维修大类不能为空'});
                common.inputOutline('.classify');
                return false;
            }
            if(this.form.catalogId == ''){
                this.$Message({type:'error',message:'维修小类不能为空'});
                return false;
            }
            if(this.starts == ''){
                this.$Message({type:'error',message:'申报位置不能为空'});
                return false;
            }
            if(this.form.desc == ''){
                this.$Message({type:'error',message:'详情描述不能为空'});
                common.inputOutline('.con-area.desc-area');
                return false;
            }
            if(this.form.contact == ''){
                this.$Message({type:'error',message:'联系人不能为空'});
                common.inputOutline('.con-area.contact-area');
                return false;
            }
            if(!this.starts.split(' ')[2]){
                this.$Message({type:'error',message:'请选择科室'});
                this.clickShowRoom()
                return false;
            }
            return true;
        },
        submit(){
            if(!this.checkForm()) return;
            if(this.isHandle){
                this.isHandle = false;
                let json = {};
                json["bigclassname"] = this.classify;
                json["smallclassname"] = this.catalog;
                json["bigclassid"] = this.form.classifyId;
                json["smallclassid"] = this.form.catalogId;
                json["site"] = this.starts;
                json["des"] = this.form.desc;
                json["tsid"] = '0';
                json["tsdestime"] = '普通单';
                json["department"] = this.fullName.length < 3 ? this.starts.split(' ')[2] : this.fullName[2];
                json["detail_addr"] = this.fullName.length < 3 ? this.starts : this.fullName.join(' ');
                json["applicant"] = this.form.contact;
                let lis = JSON.stringify(json); //转为对象（{class:""} => {"class": " "}）
                jQuery.ajax({
                    url: mtSubmitUrl,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        data: lis
                    },
                    cache: false,
                    success: function(data){
                        if(data.success){
                            this.$Message({type:'success',message:'提交成功'})
                            this.clearAll()
                        }else{
                            this.$Message({type:'error',message:data.msg});
                            this.clearAll()
                        }
                        this.isHandle = true;
                    }.bind(this),
                    error:res=>{
                        this.$Message({type:'error',message:res.status});
                        this.isHandle = true;
                    }
                })
            }

        },
        clearAll(){
            this.classify = '';
            this.catalog = '';
            this.form.classify = '';
            this.form.catalog = '';
            this.form.desc = '';
            this.form.contact = '';
        },
        //选择类型
        saveLisItem(id, title, num){   // 保存上一步选中的项    num: 大类0 小类1
            switch(num){
                case 0: this.form.classifyId = id; this.classify = title; break;
                case 1: this.form.catalogId = id; this.catalog = title; break;
            }
            if(num == 0){
                this.form.catalogId = ''
                this.catalog = ''
                if(this.catalogLis[0].title.indexOf('*') != -1){    // 当小类为*时，自动添加
                    this.saveLisItem(this.catalogLis[0].id, this.catalogLis[0].title, 1);
                    this.currType = -1;
                }else {
                    this.currType ++ ;
                }
            }
            if(num == 1){   // 当选完小类后，自动focus到详情描述
                this.isShowList = false;
                this.currType = -1;
            }
        },
        resetClassifyAndCatalog(){
            this.form.classifyId = '';
            this.form.catalogId = '';
        },
        switchClassifyLis(num){     // 0:普通大类 1:常用大类
            if(num == 0 || (num == 1 && this.isShowCommon)){
                this.classifyLis = this.dataLis.map(v => {
                    return {
                        id: v.id,
                        title: v.title
                    }
                })
                this.resetClassifyAndCatalog();
                this.isShowCommon = false;
            }else if(num == 1 && !this.isShowCommon){
                this.isShowCommon = true;
                this.catalogLis = []
                this.resetClassifyAndCatalog();
                this.classifyLis = this.topDataLis.map(v => {
                    return {
                        id: v.id,
                        title: v.title
                    }
                })
            }
            // common.inputOutline('.classify');
        },
        switchCatalogLis(id = 0, title = ''){   // 切换到小类list
            let obj = this.isShowCommon ? this.topDataLis.find(v => v.id == id) : this.dataLis.find(v => v.id == id)
            this.catalogLis = obj.smalls;
            this.saveLisItem(id, title, 0);
        },
        handleHideModal(){
            this.$emit('handleHideModal');
        }
    }
}
</script>

<style lang="less">
    @import "../assets/less/wxorder.less";
</style>
